package com.bowlong.sql;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

public class DBSupport {
	final DataSource ds;
	final QueryRunner qr;

	public DBSupport(DataSource ds) {
		this.ds = ds;
		this.qr = new QueryRunner(ds);
	}

	public void execute(final String sql) throws SQLException {
		this.qr.update(sql);
	}

	public <T> T queryForObject(final String sql, final Class<T> c)
			throws SQLException {
		return (T) this.qr.query(sql, new BeanHandler<T>(c));
	}

	public <T> T queryForObject(final String sql, final Class<T> c,
			final Object... params) throws SQLException {
		return (T) this.qr.query(sql, new BeanHandler<T>(c), params);
	}

	public Map<String, Object> queryForMap(final String sql)
			throws SQLException {
		return this.qr.query(sql, new MapHandler());
	}

	public Map<String, Object> queryForMap(final String sql,
			final Object... params) throws SQLException {
		return this.qr.query(sql, new MapHandler(), params);
	}

	public <T> List<T> queryForList(final String sql, final Class<T> c)
			throws SQLException {
		return this.qr.query(sql, new BeanListHandler<T>(c));
	}

	public <T> List<T> queryForList(final String sql, final Class<T> c,
			final Object... params) throws SQLException {
		return this.qr.query(sql, new BeanListHandler<T>(c), params);
	}

	public List<Map<String, Object>> queryForMaps(final String sql)
			throws SQLException {
		return this.qr.query(sql, new MapListHandler());
	}

	public List<Map<String, Object>> queryForMaps(final String sql,
			final Object... params) throws SQLException {
		return this.qr.query(sql, new MapListHandler(), params);
	}

	public <T> T insert(final String sql, final Class<T> c) throws SQLException {
		return this.qr.insert(sql, new BeanHandler<T>(c));
	}

	public <T> T insert(final String sql, final Class<T> c,
			final Object... params) throws SQLException {
		return this.qr.insert(sql, new BeanHandler<T>(c), params);
	}

	public int update(final String sql) throws SQLException {
		return this.qr.update(sql);
	}

	public int update(final String sql, final Object... params)
			throws SQLException {
		return this.qr.update(sql, params);
	}

}
